<template>
  <div>
    <div class="demo-input-suffix gl_searchBox">
      <el-row :gutter="20">
        <!-- 比赛日期 -->
        <el-col :md="6" :lg="4">
          <p>比赛日期</p>
          <el-select v-model="sessionQO.Day" size="mini" filterable @change="getPageData()">
            <el-option value="" label="全部" />
            <el-option v-for="item in dayData" :key="item.date" :value="item.date | FormatDate('yyyy-MM-dd')">{{ item.date | FormatDate('yyyy-MM-dd') }}</el-option>
          </el-select>
        </el-col>
        <!-- 场地选择 -->
        <el-col :md="6" :lg="4">
          <p>场地选择</p>
          <el-select v-model="sessionQO.LocationCode" size="mini" filterable @change="getPageData()">
            <el-option value="" label="全部" />
            <el-option v-for="item in locationData" :key="item.code" :label="`场地 ${item.code}`" :value="item.code" />
          </el-select>
        </el-col>
      </el-row>
    </div>
    <template>
      <el-row :gutter="20" class="gl_my_15">
        <!-- 添加时间单元设置 -->
        <el-col>
          <el-button type="primary" size="mini" @click="handleOperateEventsTime('add')">添加时间单元设置</el-button>
        </el-col>
      </el-row>
      <el-table v-loading="loading" :data="eventsTableData" stripe size="mini" style="width: 100%;">
        <!-- 比赛日期 -->
        <el-table-column label="比赛日期" align="center" width="100">
          <template slot-scope="{row}">
            <span v-if="row.day">
              {{ row.day | FormatDate('yyyy-MM-dd') }}
            </span>
          </template>
        </el-table-column>
        <!-- 比赛场地 -->
        <el-table-column prop="locationCode" label="比赛场地" width="260" align="center">
          <template slot-scope="{row}">
            场地 {{ handleLocationNameShow(row.locationCode) }}
          </template>
        </el-table-column>
        <!-- 单元内容 -->
        <el-table-column label="单元内容" align="left" min-width="200">
          <template v-if="row.competitionSessions.length > 0" slot-scope="{row}">
            <div v-for="(item, index) in row.competitionSessions" :key="index" class="unit_item" :class="row.competitionSessions.length - 1 != index ? 'gl_mr_30': ''">
              <span :class="item.type ? 'hasUnit_type' : ''">{{ item.type ? item.type + ':' : '' }}</span>
              <span>{{ item.startTime | FormatDate('HH:mm:ss') }}</span>
              —
              <span>{{ item.endTime | FormatDate('HH:mm:ss') }}</span>
            </div>
          </template>
        </el-table-column>
        <!-- 操作 -->
        <el-table-column :label="$t('table.actions')" width="150">
          <template slot-scope="{row}">
            <el-button size="mini" type="text" @click="handleOperateEventsTime('edit', row)">
              {{ $t('table.edit') }}
            </el-button>
            <el-button size="mini" type="text" @click="handleDeleteEvents(row)">
              <span class="gl_color_error">{{ $t('table.delete') }}</span>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-row class="gl_pt_20" style="text-align: center;">
        <el-pagination :current-page="sessionQO.Page" :page-size="sessionQO.MaxResultCount" :total="totalPage" layout="total,sizes,prev,pager,next,jumper" :page-sizes="[10, 20, 30, 40]" @size-change="sizeChange" @current-change="pageIndexChange" />
      </el-row>
    </template>
    <!-- 添加/修改时间单元设置 -->
    <el-dialog :title="eventsDialogName" class="gl_dialog_TitleLine" :visible.sync="dialogOperateEvents" :close-on-click-modal="false" width="660px">
      <el-scrollbar wrap-class="scrollbar-wrapper gl_dialog_height fixHeight">
        <el-form ref="refSessionInput" class="gl_form_mini" :model="sessionInput" :rules="sessionInput_Rules" label-width="120px" style="padding-right: 20px;">
          <!-- 比赛日期 -->
          <el-form-item label="比赛日期" prop="day">
            <el-select v-model="sessionInput.day" size="mini" filterable :disabled="operateType === 'edit'">
              <el-option v-for="item in dayData" :key="item.date" :value="item.date | FormatDate('yyyy-MM-dd')">{{ item.date | FormatDate('yyyy-MM-dd') }}</el-option>
            </el-select>
          </el-form-item>
          <!-- 比赛场地 -->
          <el-form-item label="比赛场地" prop="locationCodes">
            <el-checkbox-group v-model="sessionInput.locationCodes">
              <el-checkbox v-for="item in locationData" :key="item.code" :label="item.code" :disabled="operateType === 'edit'">场地{{ item.name }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <!-- <div class="gl_mb_20 gl_mx_30">
            <el-alert show-icon :closable="false" title="注意，请先选择结束时间，再选择开始时间！" type="warning" />
          </div> -->
          <div v-for="(item, index) in sessionInput.customSessions" :key="index">
            <el-form-item style="margin-left:0">
              <el-input v-model.trim="item.type" class="picker_input" placeholder="请输入单元名称" size="mini" />
              <el-time-picker
                v-model="item.eventTime"
                class="picker_time_picker"
                :default-value="[item.startTime, item.endTime]"
                is-range
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                placeholder="选择时间范围"
                format="HH:mm"
                value-format="HH:mm"
                size="mini"
                @change="timeChange"
              />
              <el-button class="picker_delet" type="danger" size="mini" @click="clickDeletSession(index, item)">删除</el-button>
            </el-form-item>
          </div>
          <div class="gl_ml_30">
            <el-button style="padding:0;" type="text" @click="clickAddSession()">+添加单元</el-button>
          </div>
        </el-form>
      </el-scrollbar>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogOperateEvents = false">{{ $t('button.cancel') }}</el-button>
        <el-button size="mini" type="primary" :loading="submitLoading" @click="handleSubmitEventsTime()">{{ $t('button.save') }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { translateByCode } from '@/lib/getTransData';
import { FormatDate } from '@/lib';
import { SessionInput_Rules } from '@/lib/validate/execte';
import {
  Api_GET_EventsManagementCompetitionSessionQO, // 查询单元列表
  SiSTKWEventsManagementCreateCompetitionSessionInput, // 新建单元
  Api_DELETE_EventsManagementCompetitionSessionByDayLocationQO // 通过比赛日场地删除单元
} from '@/lib/form/game/swaggerForm';
import {
  api_GET_EventsManagementCompetitionDay, // 获取比赛日列表
  api_GET_EventsManagementCompetitionSessionGroupByDayLocation, // 查询单元列表
  api_GET_EventsManagementCompetitionLocation, // 查询场地列表
  api_POST_EventsManagementCompetitionSessionSessionByDayLocationCustomSession, // 新建单元
  api_DELETE_EventsManagementCompetitionSessionByDayLocation, // 通过比赛日场地删除单元
  api_DELETE_EventsManagementCompetitionSessionId // 删除单元
} from '@/extend/api/gameswaggerApi/app';
// import { CopyData } from '@/lib';
export default {
  name: 'UnitSetting',
  data() {
    return {
      sessionQO: new Api_GET_EventsManagementCompetitionSessionQO(),
      sessionInput: new SiSTKWEventsManagementCreateCompetitionSessionInput(),
      deleteSessionByDayLocationQO: new Api_DELETE_EventsManagementCompetitionSessionByDayLocationQO(),
      currentPage: 1,
      totalPage: 0,
      dayData: [],
      locationData: [],
      eventsTableData: [],
      tableRow: {},
      operateType: '',
      dialogOperateEvents: false,
      eventsDialogName: '',
      sessionInput_Rules: new SessionInput_Rules(),
      loading: false,
      submitLoading: false
    };
  },
  watch: {
    dialogOperateEvents(val) {
      if (!val) {
        this.$refs.refSessionInput.resetFields();
        this.sessionInput = new SiSTKWEventsManagementCreateCompetitionSessionInput();
        this.getPageData(this.sessionQO.Page);
      }
    }
  },
  created() {
    this.sessionQO.LocationCode = '';
    api_GET_EventsManagementCompetitionDay({ competitionId: this.$route.params.id }).then(res => {
      this.dayData = res.items;
    });
    this.getCompetitionLocationList();
    this.getPageData();
  },
  methods: {
    // 获取表格数据
    getPageData(page) {
      this.loading = true;
      this.sessionQO.Page = page || 1;
      this.sessionQO.SkipCount = (this.sessionQO.Page - 1) * this.sessionQO.MaxResultCount;
      this.sessionQO.CompetitionId = this.$route.params.id;
      api_GET_EventsManagementCompetitionSessionGroupByDayLocation(this.sessionQO).then(res => {
        this.loading = false;
        this.totalPage = res.totalCount;
        this.eventsTableData = res.items;
      });
    },
    sizeChange(MaxResultCount) {
      this.sessionQO.MaxResultCount = MaxResultCount;
      this.getPageData();
    },
    pageIndexChange(currentPage) {
      this.getPageData(currentPage);
    },
    // 获取场地列表
    getCompetitionLocationList() {
      return new Promise((resolve, reject) => {
        api_GET_EventsManagementCompetitionLocation({ competitionId: this.$route.params.id }).then(res => {
          this.locationData = res.items;
        }, error => {
          this.$message({ type: 'error', message: '获取场地列表失败!' + error.error.message });
        });
      });
    },
    // 处理场地名称显示
    handleLocationNameShow(locationCode) {
      for (let i = 0; i < this.locationData.length; i++) {
        if (locationCode === this.locationData[i].code) {
          return this.locationData[i].name;
        }
      }
    },
    // 添加时间单元设置
    handleOperateEventsTime(type, row) {
      if (type === 'add') {
        this.eventsDialogName = '添加时间单元设置';
      }
      if (type === 'edit') {
        this.tableRow = JSON.parse(JSON.stringify(row)); // 深拷贝常用方法
        this.eventsDialogName = '编辑时间单元设置';
        // 手动格式化时间赋值回显
        this.sessionInput.day = FormatDate(this.tableRow.day, 'yyyy-MM-dd');
        this.sessionInput.customSessions = this.tableRow.competitionSessions;
        this.sessionInput.competitionId = this.tableRow.competitionId;
        this.sessionInput.locationCodes = [this.tableRow.locationCode];
        for (let i = 0; i < this.sessionInput.customSessions.length; i++) {
          const item = this.sessionInput.customSessions[i];
          item.startTime = item.startTime ? FormatDate(item.startTime, 'HH:mm') : '';
          item.endTime = item.endTime ? FormatDate(item.endTime, 'HH:mm') : '';
          // 需要$set 去赋值，要不然修改时间的时候页面不会渲染
          this.$set(item, 'eventTime', [item.startTime, item.endTime]);
        }
      }
      console.log(this.sessionInput);
      this.operateType = type;
      this.dialogOperateEvents = true;
    },
    change(val) {
      console.log(val);
    },
    // 校验结束时间小于开始时间
    changeRules(e, type) {
      console.log(e, type);
    },
    // 添加单元的 Session
    clickAddSession() {
      // const date = new Date();
      const _startTime = new Date(this.createTimeStr(new Date(), 'ymd') + ' 08:00:00');
      const _endTime = new Date(this.createTimeStr(new Date(), 'ymd') + ' 23:00:00');
      const customSession = {
        type: '',
        startTime: _startTime,
        endTime: _endTime,
        isAdd: true,
        eventTime: ['08:00', '23:00']
      };
      this.sessionInput.customSessions.push(customSession);
      // this.$set(this.sessionInput.customSessions[this.sessionInput.customSessions.length - 1], 'startTime', _startTime);
      // this.$set(this.sessionInput.customSessions[this.sessionInput.customSessions.length - 1], 'endTime', _endTime);
      console.log(this.sessionInput.customSessions);
    },
    /**
    * 将时间格式化为标准字符串==HH-MM-DD HH:MI:ss
    *
    *
    * */
    createTimeStr (time = new Date(), type = 'ymdhis') {
      const date = new Date(time);
      let Str = '';
      const year = date.getFullYear();
      let month = date.getMonth() + 1;
      if (month < 10)month = '0' + month;
      let day = date.getDate();
      if (day < 10) day = '0' + day;
      let hours = date.getHours();
      if (hours < 10)hours = '0' + hours;
      let minutes = date.getMinutes();
      if (minutes < 10)minutes = '0' + minutes;
      let Seconds = date.getSeconds();
      if (Seconds < 10)Seconds = '0' + Seconds;
      if (type === 'ymdhis') {
        Str = year + '-' +
          month + '-' +
            day + ' ' +
          hours + ':' +
          minutes + ':' +
          Seconds;
      } else if (type === 'ymd') {
        Str = year + '-' +
          month + '-' +
          day;
      } else if (type === 'his') {
        Str = hours + ':' +
          minutes + ':' +
          Seconds;
      }
      return Str;
    },
    // 删除单元的 Session
    clickDeletSession(index, row) {
      console.log(row);
      if (this.operateType === 'add') {
        this.sessionInput.customSessions.splice(index, 1);
      } else {
        if (row.isAdd) {
          this.sessionInput.customSessions.splice(index, 1);
        } else {
          this.$confirm(`您确定要删除 [${row.type}] 吗？`, '提示', {
            confirmButtonText: translateByCode('alert.confirm'),
            cancelButtonText: translateByCode('alert.cancel'),
            type: 'warning'
          }).then(() => {
            api_DELETE_EventsManagementCompetitionSessionId(row.id).then(res => {
              this.$message({ type: 'success', message: '操作成功！' });
              this.sessionInput.customSessions.splice(index, 1);
            }, error => {
              this.$message({ type: 'error', message: '操作失败！' + (error.error.code || error.error.message) });
            });
          });
        }
      }
    },
    // 提交 —— 添加时间单元设置
    handleSubmitEventsTime() {
      this.$refs.refSessionInput.validate(valid => {
        if (valid) {
          if (this.sessionInput.customSessions.length > 0) {
            const _hasEmptySession = this.hasEmptySession(this.sessionInput.customSessions);
            if (_hasEmptySession) {
              this.submitLoading = true;
              const _sessionInput = JSON.parse(JSON.stringify(this.sessionInput));
              // 处理日期格式
              _sessionInput.day = FormatDate(_sessionInput.day, 'yyyy-MM-dd HH:mm:ss');
              const _day = _sessionInput.day.substring(0, 10);
              _sessionInput.competitionId = this.$route.params.id;
              for (let i = 0; i < _sessionInput.customSessions.length; i++) {
                const item = _sessionInput.customSessions[i];
                item.startTime = item.eventTime && item.eventTime[0] ? `${_day} ${item.eventTime[0]}` : null;
                item.endTime = item.eventTime && item.eventTime[1] ? `${_day} ${item.eventTime[1]}` : null;
                if (item.startTime === item.endTime) {
                  this.$message({ type: 'warning', message: `单元${item.type}的开始时间与结束时间不能相同` });
                  this.submitLoading = false;
                  return;
                }
              }
              console.log(_sessionInput);
              api_POST_EventsManagementCompetitionSessionSessionByDayLocationCustomSession(_sessionInput)
                .then(res => {
                  this.submitLoading = false;
                  this.dialogOperateEvents = false;
                  this.getPageData();
                  this.$message({ type: 'success', message: '操作成功' });
                })
                .catch(
                  error => {
                    this.submitLoading = false;
                    this.$message({ type: 'error', message: error.error.message });
                  }
                );
            }
          } else {
            // 判断如果没有选上中下午任意一个则给提示信息
            this.$message({ type: 'warning', message: '请选择一个时间区间，否则无法添加单元！' });
            this.submitLoading = false;
          }
        } else {
          this.submitLoading = false;
          return false;
        }
      });
    },
    hasEmptySession (data) {
      for (let i = 0; i < data.length; i++) {
        const item = data[i];
        if (!item.type) {
          this.$message({ type: 'warning', message: '请输入单元名称！' });
          return false;
        }
        for (let j = 0; j < item.eventTime.length; j++) {
          const jtem = item.eventTime[j];
          if (!jtem) {
            this.$message({ type: 'warning', message: '请输入单元时间！' });
            return false;
          }
        }
      }
      return true;
    },
    // 提交 —— 修改时间单元设置
    handleEdit() {
      this.$refs.refSessionInput.validate(valid => {
        this.submitLoading = true;
        if (valid) {
          if (this.sessionInput.customSessions.length > 0) {
            api_POST_EventsManagementCompetitionSessionSessionByDayLocationCustomSession(this.tableRow.id, this.sessionInput).then(res => {
              this.submitLoading = false;
              this.dialogOperateEvents = false;
              this.getPageData();
              this.$message({ type: 'success', message: '操作成功' });
            });
          } else {
            // 判断如果没有选上中下午任意一个则给提示信息
            this.$message({ type: 'warning', message: '请选择一个时间区间，否则无法添加单元！' });
            this.submitLoading = false;
          }
        } else {
          this.submitLoading = false;
          return false;
        }
      });
    },
    // 删除单元
    handleDeleteEvents(row) {
      this.deleteSessionByDayLocationQO.CompetitionId = row.competitionId;
      this.deleteSessionByDayLocationQO.Date = row.day;
      this.deleteSessionByDayLocationQO.LocationCode = row.locationCode;
      this.$confirm(`您确定要删除 [场地 ${row.locationCode}] 吗？`, '提示', {
        confirmButtonText: translateByCode('alert.confirm'),
        cancelButtonText: translateByCode('alert.cancel'),
        type: 'warning'
      }).then(() => {
        api_DELETE_EventsManagementCompetitionSessionByDayLocation(this.deleteSessionByDayLocationQO).then(res => {
          this.getPageData(this.sessionQO.Page);
          this.$message({ type: 'success', message: '操作成功！' });
        }, error => {
          this.$message({ type: 'error', message: '操作失败！' + (error.error.code || error.error.message) });
        });
      });
    },
    timeChange(val) {
      console.log(val);
    }
  }
};
</script>
<style lang="scss" scoped>
  .picker_input{
    width: 130px;
    position: absolute;
    left: -89px;
    top: 1px;
  }
  .picker_time_picker{
    margin-left: 50px;
  }
  .picker_delet{
    position: absolute;
    right: 15px;
    top: 2px;
  }
  .unit_item{
    display: inline-block;
  }
  .hasUnit_type{
    display: inline-block;
    margin-right: 10px;
  }
</style>
